﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using _2QWebProxy.App_Code;
using System.Net;

namespace _2QWebProxy.GUI
{
    public partial class ucPrivacyIPAddress : UserControl
    {
        public bool isDenyForm = false;

        public ucPrivacyIPAddress(bool isDenyForm)
        {
            this.isDenyForm = isDenyForm;
            InitializeComponent();
            LoadIPAddressList();
        }

        private void LoadIPAddressList()
        {
            if (isDenyForm)
            {
                List<PrivacyIpAddress> ipAddresses = Utils.GetPrivacyIPAddress("deny");
                dgvPrivacyIPAddress.DataSource = ipAddresses;
            }
            else
            {
                List<PrivacyIpAddress> ipAddresses = Utils.GetPrivacyIPAddress("allow");
                dgvPrivacyIPAddress.DataSource = ipAddresses;
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            IPAddress address;
            if (IPAddress.TryParse(txtIPAddress.Text, out address))
            {
                if (isDenyForm)
                {
                    SaveIPAddress("deny");
                }
                else
                {
                    SaveIPAddress("allow");
                }
                LoadIPAddressList();
            }
            else
            {
                MessageBox.Show("Invalid IPAddress");
            }
        }

        private void SaveIPAddress(string status)
        {
            PrivacyIpAddress ipAddress = new PrivacyIpAddress()
            {
                Name = txtIPAddress.Text,
                Status = status
            };
            Utils.SaveIPAddress(ipAddress);
        }

        private void btnRemove_Click(object sender, EventArgs e)
        {
            PrivacyIpAddress ipAddress = new PrivacyIpAddress()
            {
                Name = txtIPAddress.Text
            };

            Utils.DeletePrivacyIPAddress(ipAddress);
            LoadIPAddressList();
        }

        private void btnRemoveAll_Click(object sender, EventArgs e)
        {
            Utils.DeleteAllPrivacyIPAddress();
            LoadIPAddressList();
        }

        private void dgvPrivacyIPAddress_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            int index = dgvPrivacyIPAddress.SelectedCells[0].RowIndex;
            txtIPAddress.Text = dgvPrivacyIPAddress.Rows[index].Cells[0].Value.ToString();
        }

    }
}
